package org.takeback.chat.store.user;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.math.RandomUtils;
import org.takeback.chat.entity.GcLottery;
import org.takeback.chat.entity.Message;
import org.takeback.chat.entity.PcEggLog;
import org.takeback.chat.lottery.Lottery;
import org.takeback.chat.lottery.listeners.GameException;
import org.takeback.chat.service.LHHPlanService;
import org.takeback.chat.service.LotteryService;
import org.takeback.chat.service.RoomService;
import org.takeback.chat.store.pcegg.PcEggStore;
import org.takeback.chat.store.room.LotteryFactory;
import org.takeback.chat.store.room.Room;
import org.takeback.chat.utils.Const;
import org.takeback.chat.utils.MessageUtils;
import org.takeback.util.ApplicationContextHolder;
import org.takeback.util.BeanUtils;

public class RobotUser extends User implements Runnable {
	
	LotteryService lotteryService;
	
	LHHPlanService lHHPlanService;//龙虎合服务
	
	RoomService roomService;
	
	public static final Integer level = Integer.valueOf(1);
	public static String[] talkList = { "来个豹子...", "卧槽,今天手气好像差了点", "给我回点血吧!!!!!", "我打算收手了,草 再抢剁手了", "呵呵 我看着你剁了",
			"我今天看到个妹子,大街上就嘘嘘了起来,城里人真会玩", "感觉有点恶搞", "妈的老是我,,", "谁允许我唱首歌啊  这个软件啥都好,就是不能语音", "瓦里格气 我能说的只有圈圈和叉叉了",
			"我是一个小毛驴我从来都不齐", "好无聊啊........." };
	private Room room;

	
	public RobotUser() {
		super.setUserType("0");
		this.lotteryService = ((LotteryService) ApplicationContextHolder.getBean("lotteryService"));
		this.lHHPlanService = ((LHHPlanService) ApplicationContextHolder.getBean("lHHPlanService"));
		this.roomService = ((RoomService) ApplicationContextHolder.getBean("roomService"));
	}

	public void setRoom(Room rm) {
		this.room = rm;
	}

	public void run() {
		try {
			while (!Thread.interrupted()) {
				Long random = Long.valueOf(Math.round(10.0D * Math.random()));
				TimeUnit.SECONDS.sleep(random.longValue() + level.intValue());
				if (this.room.getType().startsWith("G01")) {
					playG01();
				} else if (this.room.getType().startsWith("G02")) {
					playG02();
				} else if (this.room.getType().startsWith("G03")) {
					playG03();
				} else if (this.room.getType().startsWith("G04")) {
					playG04();
				} else if (this.room.getType().startsWith("G07")) {
					playG07();
				}
				long r1 = Math.round(10.0D * Math.random());
				TimeUnit.SECONDS.sleep(r1 + level.intValue());
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			Thread.currentThread().interrupt();
			return;
		}
	}
	
	//获取
	public int radomYazhu(int max,int min) {
		Random random = new Random();
	    int s = random.nextInt(max)%(max-min+1) + min;
	    return s;
	}
	//机器人押注
	public String robitYazhu() {
		
		return null;
	}

	public int getDelayTime() {
		int max=80;
        int min=50;
        Random random = new Random();
        int s = random.nextInt(max)%(max-min+1) + min;
        return s*100;
	}
	private void playG07() {
		System.out.println("机器人抢包进来111了");
		try {
			Thread.sleep(getDelayTime());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Lottery lottery = getOpenableLottery();
		Map<String, Object> p = roomService.getRoomProperties(this.room.getId());
		Integer robotAction = Integer.valueOf(p.get("config_lhl_stop_or_start").toString());
//		1表示机器人可以抢，0表示停止抢,2表示机器人押注
		if(robotAction == 1 && lottery != null) {
			try {
				lottery.open(getId().intValue());
			} catch (GameException localGameException) {
				
			}
			return;
		} else if (robotAction == 2) {
//			Message msg = new Message();
//			msg.setContent("某某押注了100单注3");
//			msg.setHeadImg(getHeadImg());
//			msg.setSender(getId());
//			msg.setNickName(getUserId());
//			msg.setType(Message.TXT_SYS);
//			MessageUtils.broadcast(this.room, msg);
		} else {
		}
	}
	private void playG01() {
		Lottery lottery = getOpenableLottery();
		Map<String, Object> p = this.room.getProperties();
		Integer rest = Integer.valueOf(2);
		try {
			rest = Integer.valueOf(p.get("conf_rest_time").toString());
			rest = Integer.valueOf(rest.intValue() + 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (lottery != null) {
			if ((new Date().getTime() - lottery.getCreateTime().getTime()) / 1000L <= rest.intValue()) {
				return;
			}
			try {
				lottery.open(getId().intValue());
			} catch (GameException localGameException) {
			}
		}
	}

	private void playG02() {
		Lottery lottery = getOpenableLottery();
		if (lottery != null) {
			try {
				lottery.open(getId().intValue());
			} catch (GameException localGameException1) {
			}
		} else if (this.room.getMaster().equals(getId())) {
			Integer num = Integer.valueOf(this.room.getProperties().get("conf_size").toString());

			Lottery lottery2 = LotteryFactory.getDefaultBuilder(new BigDecimal(0.5D * num.intValue()), num).setType("2")
					.setSender(getId().intValue()).setDescription("恭喜发财,怕死别来!").setRoom(this.room).build();
			this.room.setMasterStamp(Long.valueOf(System.currentTimeMillis()));
			GcLottery gcLottery = (GcLottery) BeanUtils.map(lottery2, GcLottery.class);
			this.lotteryService.save(GcLottery.class, gcLottery);
			try {
				lottery2.fakeOpen(getId().intValue());
			} catch (GameException e) {
				e.printStackTrace();
				return;
			}
			Message redMessage = new Message(Message.RED, getId(), lottery2);
			redMessage.setHeadImg(getHeadImg());
			redMessage.setNickName(getNickName());
			MessageUtils.broadcast(this.room, redMessage);
		}
	}

	private void playG03() {
		PcEggLog log = PcEggStore.getStore().getLastest();
		Calendar c = Calendar.getInstance();
		c.setTime(log.getExpireTime());
		c.add(13, -30);
		if (c.getTime().compareTo(new Date()) < 0) {
			return;
		}
		String[] games = { "大", "小", "单", "双", "大单", "大双", "小双", "小单", "极大", "极小", "红", "黄", "蓝" };
		int d = (int) Math.round(Math.random() * 10.0D);
		if ((d == 0) || (d % 4 == 0)) {
			return;
		}
		long game = Math.round(d) % games.length;
		if (game == games.length) {
			game -= 1L;
		}
		Double money = Double.valueOf(Math.random() * 100.0D);

		Lottery lottery = LotteryFactory.getDefaultBuilder(new BigDecimal(money.doubleValue()), Integer.valueOf(1))
				.setExpiredSeconds(Integer.valueOf(1)).setType("2").setTitle(games[((int) game)] + " " + d * 5 + "元")
				.setSender(getId().intValue()).setDescription(log.getId() + "期").build();
		try {
			lottery.open(0);
		} catch (GameException e) {
			e.printStackTrace();
		}
		Message redMessage = new Message(Message.RED, getId(), lottery);
		redMessage.setHeadImg(getHeadImg());
		redMessage.setNickName(getNickName());
		MessageUtils.broadcast(this.room, redMessage);
	}

	private void playG04() {
		Map<String, Object> p = this.room.getProperties();
		Integer size = Integer.valueOf(p.get("conf_max_size").toString());
		Integer money = Integer.valueOf(p.get("conf_max_money").toString());
		Double rate = this.room.getFeeAdd();

		Lottery lottery = getOpenableLottery();
		if (lottery != null) {
			try {
				lottery.open(getId().intValue());
			} catch (GameException localGameException) {
			}
		} else {
            final Integer raidPoint = RandomUtils.nextInt(9);
            final Lottery lottery2 = LotteryFactory.getDefaultBuilder(new BigDecimal(money * (1.0 - rate)), size).setType("2").setSender(this.getId()).setDescription(money * (1.0 - rate) + "\u91d1\u5e01/\u96f7" + raidPoint).setRoom(this.room).build();
            this.room.setMasterStamp(System.currentTimeMillis());
			this.room.getProperties().put(Const.PROP_RAID, raidPoint);
			GcLottery gcLottery = (GcLottery) BeanUtils.map(lottery2, GcLottery.class);
			this.lotteryService.save(GcLottery.class, gcLottery);
			Message redMessage = new Message(Message.RED, getId(), lottery2);
			redMessage.setHeadImg(getHeadImg());
			redMessage.setNickName(getNickName());
			MessageUtils.broadcast(this.room, redMessage);
		}
	}

	public void talk() {
		long r = Math.round(10.0D * Math.random());
		if (r > 0L) {
			r = r % talkList.length - 1L;
		} else if (r < 0L) {
			r = 0L;
		}
		Message msg = new Message();
		msg.setContent(talkList[((int) r)]);
		msg.setHeadImg(getHeadImg());
		msg.setSender(getId());
		msg.setNickName(getUserId());
		msg.setType(Message.TXT);
		MessageUtils.broadcast(this.room, msg);
	}

	//得到房间没有领的红包
	private Lottery getOpenableLottery() {
		Map<String, Lottery> lts = this.room.getLotteries().asMap();

		Iterator itr = lts.keySet().iterator();
		while (itr.hasNext()) {
			String key = (String) itr.next();
            final Lottery lottery = lts.get(key);
			if (("0".equals(lottery.getStatus())) && (lottery.isOpen()) && (!lottery.isExpired())) {
				return lottery;
			}
		}
		return null;
	}

	public static void main(String... args) {
		for (;;) {
			System.out.println(RandomUtils.nextInt(10));
		}
	}
}
